﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ext.Net;
using Sharp.Portal.Other;

namespace Sharp.Portal.ExtNet
{
    /// <summary>
    /// 工具栏代码具体实现
    /// </summary>
    public class ExtToolButtons : IToolButton
    {
        /// <summary>
        /// 工具栏代码具体实现
        /// </summary>
        public ExtToolButtons()
        {
        }
        /// <summary>
        /// 列表页
        /// </summary>
        public dynamic ListPage { get; set; }
        /// <summary>
        /// 详情按钮
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public string DetailsButton(ToolButtonInfo config)
        {
            config.Icon = "Icon.ApplicationForm";

            if (config.Direct == null)
            {
                config.OnClientClick = string.Format(
                    "App.Grid.OnModuleOperation(this,'\" + Url.Action(\"{0}\") + \"',{{[参数]}});",
                    string.Join("\",\"", config.UrlAction.Split(',')));

                AddFieldProperty(config, "IsReadOnlyForm", true);
            }
            if (string.IsNullOrEmpty(ListPage.ItemPanelUrlAction))
            {
                ListPage.ItemPanelUrlAction = config.UrlAction;
            }

            return CustomButton(config);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        public string CreateButton(ToolButtonInfo config)
        {
            config.Icon = "Icon.Add";
            if (config.Direct == null)
            {
                config.OnClientClick = string.Format(
                    "App.Grid.OnModuleOperation(this,'\" + Url.Action(\"{0}\") + \"',{{[参数]}});",
                    string.Join("\",\"", config.UrlAction.Split(',')));

                AddFieldProperty(config, "ShowOnly", true);
            }
            config.Parameters.Add(new ToolButtonInfo.Parameter("refreshGrid", "App.Grid.refreshGrid(this)", (int)ParameterMode.Raw));

            return CustomButton(config);
        }

        /// <summary>
        /// 编辑按钮
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public string EditButton(ToolButtonInfo config)
        {
            config.Icon = "Icon.ApplicationFormEdit";
            if (config.Direct == null)
            {
                config.OnClientClick = string.Format(
                    "App.Grid.OnModuleOperation(this,'\" + Url.Action(\"{0}\") + \"',{{[参数]}});",
                    string.Join("\",\"", config.UrlAction.Split(',')));
            }
            config.Parameters.Add(new ToolButtonInfo.Parameter("refreshGrid", "App.Grid.refreshGrid(this)", (int)ParameterMode.Raw));
            return CustomButton(config);
        }
        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public string DeleteButton(ToolButtonInfo config)
        {
            config.Icon = "Icon.Delete";
            if (config.Direct == null)
                config.OnClientClick = string.Format(
                    "App.Grid.OnModuleOperation(this,'\" + Url.Action(\"{0}\") + \"',{{[参数]}});",
                    string.Join("\",\"", config.UrlAction.Split(',')));

            AddFieldProperty(config, "IsAjax", true);
            config.Parameters.Add(new ToolButtonInfo.Parameter("refreshGrid", "App.Grid.refreshGrid(this)", (int)ParameterMode.Raw));

            return CustomButton(config);
        }
        /// <summary>
        /// 刷新按钮
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public string RefreshButton(ToolButtonInfo config)
        {
            config.Icon = "Icon.TableRefresh";
            config.OnClientClick = "App.Grid.Refresh(this)";
            return CustomButton(config);
        }

        /// <summary>
        /// 自定义按钮
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public string CustomButton(ToolButtonInfo config)
        {
            StringBuilder sb = new StringBuilder("x.Button()");
            sb.AppendFormat(".Text(\"{0}\")", config.Title);
            if (!config.Icon.IsNullOrEmpty())
            {
                sb.AppendFormat(".Icon({0})", config.Icon);
            }
            sb.Append(".Hidden(Model.Editable())");
            if (!config.OnClientClick.IsNullOrEmpty())
            {
                sb.AppendFormat(".OnClientClick(\"{0}\")", config.OnClientClick);

                //客户端参数只支持js、固定字符串，不支持服务端代码
                if (config.Parameters != null && config.Parameters.Any())
                {
                    foreach (var p in config.Parameters)
                    {
                        var pm = (ParameterMode)p.Mode;
                        if (pm == ParameterMode.Raw)
                        {
                            config.ClientClickExtraParams[p.Name] = p.Value;
                        }
                        else if (pm == ParameterMode.Auto)//借用Auto作服务器代码的传递
                        {
                            config.ClientClickExtraParams[p.Name] = string.Format("'\" + {0} + \"'", p.Value);
                        }
                        else
                        {
                            config.ClientClickExtraParams[p.Name] = string.Format("'{0}'", p.Value);
                        }

                    }
                }

                sb.Replace("[参数]",
                    string.Join(",",
                        config.ClientClickExtraParams.Select(f => string.Format("{0} : {1}", f.Key, f.Value))));
                return sb.ToString();
            }
            
            if (config.Direct != null)
            {
                sb.AppendFormat(".DirectClickAction(\"{0}\", \"{1}\")", config.Direct.ActionName,
                    config.Direct.ControllerName);
            }
            if (config.Parameters != null && config.Parameters.Any())
            {
                sb.AppendLine(".DirectEvents(de =>");
                sb.AppendLine("{");
                sb.AppendLine("de.Click.EventMask.Msg = \"正在打开...\";");
                sb.AppendLine("de.Click.EventMask.ShowMask = true;");
                foreach (var p in config.Parameters)
                {
                    var pm = (ParameterMode)p.Mode;
                    if (pm == ParameterMode.Value)
                    {
                        sb.AppendFormat(
                            "de.Click.ExtraParams.Add(new Parameter(\"{0}\", {1} , ParameterMode.{2}));\r\n",
                            p.Name, p.Value, pm.ToString());
                    }
                    else
                    {
                        sb.AppendFormat(
                            "de.Click.ExtraParams.Add(new Parameter(\"{0}\", \"{1}\", ParameterMode.{2}));\r\n",
                            p.Name, p.Value, pm.ToString());
                    }
                }
                sb.AppendLine("})");
            }

            return sb.ToString();
        }

        /// <summary>
        /// 加入表单字段属性
        /// </summary>
        /// <param name="config"></param>
        /// <param name="propertyName">属性名字</param>
        /// <param name="value">布尔值属性值</param>
        private void AddFieldProperty(ToolButtonInfo config, string propertyName, Boolean value)
        {
            config.ClientClickExtraParams[propertyName] = string.Format("{0}", value.ToString().ToLower());
        }


        /// <summary>
        /// 加入表单字段属性
        /// </summary>
        /// <param name="config"></param>
        /// <param name="propertyName">属性名字</param>
        /// <param name="value">字符串属性值</param>
        /// <param name="entryString">实体字符串，不加''</param>
        private void AddFieldProperty(ToolButtonInfo config, string propertyName, string value,
            Boolean entryString = false)
        {
            if (!config.ClientClickExtraParams.ContainsKey(propertyName))
                config.ClientClickExtraParams.Add(propertyName, string.Empty);
            if (entryString || propertyName == "regex")
                config.ClientClickExtraParams[propertyName] = string.Format("'{0}'", value);
            else
            {
                config.ClientClickExtraParams[propertyName] = value.ToJson();
            }
        }
    }
}